package jdbc;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCTest2 {
    public static void main(String[] args) throws SQLException {
        // 1. 创建数据源对象
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("000000");

        // 2. 建立网络连接
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

        // 3. 构建 sql 语句
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);

        // 4. 执行 sql
        ResultSet resultSet = statement.executeQuery();

        // 5. 遍历结果集合
        while(resultSet.next()){
            System.out.println(resultSet.getInt("id"));
            System.out.println(resultSet.getString("name"));
        }

        // 6. 关闭对应的资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}